package com.atguigu.spzx.product.service.impl;

import com.atguigu.spzx.model.entity.system.Category;
import com.atguigu.spzx.product.mapper.CategoryMapper;
import com.atguigu.spzx.product.service.CategoryService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.util.List;
import java.util.stream.Collectors;

@Service
public class CategoryServiceImpl implements CategoryService {

    @Autowired
    private CategoryMapper categoryMapper;
    @Override
    public List<Category> categoryList() {
        List<Category> categoryList =categoryMapper.findData();
        return categoryList;
    }

    @Override
    public List<Category> findCategoryTree() {
        //先查出所有的分类
        List<Category> categoryList = categoryMapper.findAll();
        //筛选出一级分类
        List<Category> oneCategoryList = categoryList.stream().filter(item -> item.getParentId().longValue() == 0).toList();

        //遍历一级分类,筛选出字类
        if (!CollectionUtils.isEmpty(oneCategoryList)){//如果一级分类不为空
            oneCategoryList.forEach(oneCategory ->{
                //筛选出二级分类,二级分类的parentId=一级分类的id
                List<Category> twoCategoryList = categoryList.stream().filter(item -> item.getParentId().longValue() == oneCategory.getId().longValue()).collect(Collectors.toList());
                oneCategory.setChildren(twoCategoryList);
                //筛选出三级分类,
                if(!CollectionUtils.isEmpty(twoCategoryList)){
                    twoCategoryList.forEach(twoCategory ->{
                        List<Category> threeCategory = categoryList.stream().filter(item -> item.getParentId().longValue() == twoCategory.getId().longValue()).collect(Collectors.toList());
                        twoCategory.setChildren(threeCategory);
                    });
                }
            });
        }

        return oneCategoryList;
    }
}
